/**
 * 
 */
package com.application.Activity;

import java.util.ArrayList;

import it.unipr.ce.dsg.s2p.sip.Address;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.AccountDTO;
import com.application.DTO.RoleDTO;
import com.application.DataProvider.AccountDAO;
import com.application.DataProvider.LearnerDAO;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;
import com.application.outdoor.InvoikeServices.HeThongInvoike;
import com.google.android.gcm.GCMRegistrar;

/**
 * @author TAI
 * 
 */
public class FrmLogin extends Activity {
	EditText _txtUsername;
	EditText _txtPassword;
	private static String _pass;
	CheckBox _chkRemember;
	private static ProgressDialog _dialog;
	Button _btnLogin;
	LinearLayout _llo_banner;
	Address _address;
	AccountDAO aDao = new AccountDAO(null);
	private static final int EDIT_ID = Menu.FIRST + 2;

	// outdoor
	ProgressDialog mProgressDialog;
	AsyncTask<String, Void, Integer> mDangNhapTask;
	String regId = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.frm_dangnhap);
		//Tạo các thư mục cần thiết cho ứng dụng
		ReadWriteFileController.createDirectionFolder();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String ip = prefs.getString(PrefActivity.PREF_SET_UP_IP_HOST, "192.168.2.1");
		ip += ":5033";
		NetworkController.set_ipHost(ip);
		NetworkController
				.set_statusLogin(Integer.parseInt(prefs.getString(PrefActivity.PREF_SET_UP_LOGIN_STATUS, "1")));
		NetworkController.set_isOffline(prefs.getBoolean(PrefActivity.PREF_SET_UP_OFFLINE, false));
		// =====IP SERVER======
		Protocol.SERVER_URL = prefs.getString(PrefActivity.PREF_SET_UP_IP_SERVER,
				"http://192.168.1.100:80/MES-OutDoorqw");
		// =======
		_txtUsername = (EditText) findViewById(R.id.frmdangnhap_txtusername);
		_txtPassword = (EditText) findViewById(R.id.frmdangnhap_txtpassword);
		_chkRemember = (CheckBox) findViewById(R.id.frmdangnhap_chkremember);

		_btnLogin = (Button) findViewById(R.id.frmdangnhap_btndangnhap);
		// initProgressDialog();
		_btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String userName = _txtUsername.getText().toString();
				String pass = _txtPassword.getText().toString();
				_pass = pass;

				/* lưu nhớ account */ 
				// ghi thông tin xuống file nếu check ghi nhớ
				if (_chkRemember.isChecked())
					ReadWriteFileController.WriteAccount(userName, pass, true);
				else
					ReadWriteFileController.WriteAccount(userName, pass, false);
				// FrmSubject.set_isWait(true);
				if (NetworkController.isOffline()) {
					Log.d("PEERDROID", "offline");
					if (aDao.isExist(userName)) {
						String uName = userName;
						String sPass = aDao.getPass(uName);

						LearnerDAO lDao = new LearnerDAO(null);
						int idClass = lDao.getIDClass(userName);

						Log.d("PEERDROID", "UserNAme:" + uName);
						Log.d("PEERDROID", "pass:" + sPass);
						Log.d("PEERDROID", "IDClass:" + idClass);
						if (userName.equals(uName) && pass.equals(sPass)) {
							startActivity(new Intent(getBaseContext(), FrmTabActivity.class));
							NetworkController.set_idClass(idClass);
							NetworkController.set_userName(userName);
						} else
							ShowLoginFailOffline();
					} else
						ShowLoginFailOffline();
				} else if (NetworkController.isInDoor()) {
					Log.d("PEERDROID", "indoor");
					String s = NetworkController.get_ipHost();
					_address = new Address(s);
					if (userName.equals(""))
						ShowError();
					else if (pass.equals(""))
						ShowError();
					else {
						// kiem tra nguoi dung ton tai
						if (aDao.isExist(userName)) {
							{
								Log.d("PEERDROID", "tao peer");
								NetworkController.init("DangNhap", 5033);
								Log.d("PEERDROID", "Bat dau send ID cho giao vien");
								NetworkController.Login(_address, userName, pass);

								final String uName = userName;
								final String password = pass;
//								final int avarta = aDao.getAvarta(uName);
								set_dialog(ProgressDialog.show(FrmLogin.this, "", "Connecting ...", true));
								CountDownTimer timer = new CountDownTimer(15000, 1000) {
									@Override
									public void onTick(long millisUntilFinished) {

										Thread bg = new Thread(new Runnable() {
											@Override
											public void run() {
												try {

													if (NetworkController.is_isLogin() == 2) {
														NetworkController.set_isLogin(3);
														if (!aDao.isExist(uName)) {
															aDao.insertAccount(uName, password);
														}
														Log.i("Phu", "success");
														// tạo các thư mục cần
														// thiết cho ứng dụng:
														// NetworkController.get_threadConnectToUser().start();
														Log.d("PEERDROID",
																"count thread login: " + Thread.activeCount());
//														ReadWriteFileController.createDirectionFolder();
														NetworkController._peer.account = new AccountDTO();
														NetworkController._peer.account.set_Username(uName);
														NetworkController._peer.account.set_Password(password);
//														NetworkController._peer.account.set_Avarta(avarta);

														startActivity(new Intent(getBaseContext(), FrmTabActivity.class));

														finish();
														Log.i("Phu", "finish");
													}
												} catch (Throwable t) {
													Log.d("PEERDROID", "Loi Login " + t.getMessage());
												}
											}
										});
										bg.start();
									}

									@Override
									public void onFinish() {
										if (NetworkController.is_isLogin() == 0) {
											get_dialog().dismiss();
											ShowConnectFail();
										}
										if (NetworkController.is_isLogin() == 1) {
											NetworkController.set_isLogin(0);
											get_dialog().dismiss();
											ShowLoginFail();
										}
									}
								}.start();
							}
						} else
							ShowLoginFailOffline();
					}
				} else if (NetworkController.isOutDoor()) {
					// SharedPreferences prefs =
					// PreferenceManager.getDefaultSharedPreferences(FrmLogin.this);
					// Protocol.SERVER_URL
					// =prefs.getString(PrefActivity.PREF_SET_UP_IP_SERVER,
					// "http://192.168.1.100:80/MES-OutDoorqw");
					Log.d(Protocol.TAG, "Đang nhập nè " + Protocol.SERVER_URL);
					Log.d("PEERDROID", "outdoor");
					initProgressDialog();
					initDangNhapTask();
					regId = GCMRegistrar.getRegistrationId(FrmLogin.this);
					mDangNhapTask.execute(_txtUsername.getText().toString(), _txtPassword.getText().toString(), regId);
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Cài đặt đăng nhập").setIcon(R.drawable.setting_host_ip)
				.setAlphabeticShortcut('e');
		return (super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case EDIT_ID:
			startActivity(new Intent(this, PrefActivity.class));
			return (true);

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// if(NetworkController.is_isLogin()==2)
			// NetworkController.SendMessageLogout();
			// NetworkController.set_isLogin(0);
			// if(!NetworkController.isOffline())
			// NetworkController.peerRelease();

			String userName = _txtUsername.getText().toString();
			String pass = _txtPassword.getText().toString();
			if (_chkRemember.isChecked())
				ReadWriteFileController.WriteAccount(userName, pass, true);
			else
				ReadWriteFileController.WriteAccount(userName, pass, false);

			Log.d("PEERDROID", "Đã thoát khỏi chương trình");
			finish();
			System.exit(0);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String ip = prefs.getString(PrefActivity.PREF_SET_UP_IP_HOST, "192.168.2.1");
		ip += ":5033";
		// =====IP SERVER======
		Protocol.SERVER_URL = prefs.getString(PrefActivity.PREF_SET_UP_IP_SERVER,
				"http://192.168.1.100:80/MES-OutDoorqw");
		// =======
		NetworkController.set_ipHost(ip);
		NetworkController
				.set_statusLogin(Integer.parseInt(prefs.getString(PrefActivity.PREF_SET_UP_LOGIN_STATUS, "1")));

		NetworkController.set_isOffline(prefs.getBoolean(PrefActivity.PREF_SET_UP_OFFLINE, false));

		outDoorReset();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		if (!NetworkController.isOffline())
			if (NetworkController.get_peer() != null)
				NetworkController.peerRelease();
		outDoorReset();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		// finish();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void ShowError() {
		AlertDialog.Builder alert = new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Tài khoản hoặc Mật Khẩu không được trống");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
	}

	private void ShowLoginFailOffline() {
		AlertDialog.Builder alert = new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Tài khoản hoặc Mật Khẩu không đúng");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
	}

	private void ShowLoginFail() {
		AlertDialog.Builder alert = new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Tài khoản hoặc Mật Khẩu không đúng");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
		// tắt peer
		Log.d("PEERDROID", "tắt peer");
		if (NetworkController.get_peer() != null)
			NetworkController.peerRelease();
	}

	private void ShowConnectFail() {
		AlertDialog.Builder alert = new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error Connect");
		alert.setMessage("Kết nối không được tới máy chủ !");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
		// tắt peer
		Log.d("PEERDROID", "Tắt peer");
		if (NetworkController.get_peer() != null)
			NetworkController.peerRelease();
	}

	private void ShowRegFail() {
		AlertDialog.Builder alert = new AlertDialog.Builder(FrmLogin.this);
		alert.setTitle("Error");
		alert.setMessage("Kiểm tra lại tài khoản của thiết bị");
		alert.setPositiveButton("Đồng ý", null);
		alert.create().show();
		// tắt peer
		Log.d("PEERDROID", "tắt peer");
		if (NetworkController.get_peer() != null)
			NetworkController.peerRelease();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		// lấy thông tin ip host để đăng nhập
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String ip = prefs.getString("txt_ip_host", "192.168.2.1");
		ip += ":5033";
		// =====IP SERVER======
		Protocol.SERVER_URL = prefs.getString(PrefActivity.PREF_SET_UP_IP_SERVER,
				"http://192.168.1.100:80/MES-OutDoorqw");
		// =======
		NetworkController.set_ipHost(ip);

		NetworkController
				.set_statusLogin(Integer.parseInt(prefs.getString(PrefActivity.PREF_SET_UP_LOGIN_STATUS, "1")));
		NetworkController.set_isOffline(prefs.getBoolean(PrefActivity.PREF_SET_UP_OFFLINE, false));
		// if(!NetworkController.isOffline())
		// {
		//
		// if(NetworkController.get_peer()==null)
		// {
		// Log.d("PEERDROID","tao peer");
		// NetworkController.init("DangNhap", 5033);
		//
		// }
		// }
		ActivityController.setPeerActivity(this);
		ArrayList<String> acc;
		Log.d("PEERDROID", "load file");
		String path = Environment.getExternalStorageDirectory().toString() + "/account.xml";
		try {
			acc = ReadWriteFileController.ReadAccount(path);
			if (acc.size() != 0) {
				// if(acc.get(2).equals("true"))
				_chkRemember.setChecked(true);
				// else
				// _chkRemember.setChecked(false);

				if (_chkRemember.isChecked()) {
					_txtUsername.setText(acc.get(0));
					_txtPassword.setText(acc.get(1));
				}
			} else
				_chkRemember.setChecked(false);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	public static void set_dialog(ProgressDialog _dialog) {
		FrmLogin._dialog = _dialog;
	}

	public static ProgressDialog get_dialog() {
		return _dialog;
	}

	public static void set_pass(String _pass) {
		FrmLogin._pass = _pass;
	}

	public static String get_pass() {
		return _pass;
	}

	public void Show(String message) {

		AlertDialog dlg = new AlertDialog.Builder(this).setTitle("Thông báo").setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).create();
		dlg.show();
	}

	private void initProgressDialog() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("Đang kết nối tới máy chủ!\n" + Protocol.SERVER_URL);
		mProgressDialog.setButton("Hủy bỏ", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDangNhapTask.cancel(true);
			}
		});
	}

	private void initDangNhapTask() {
		mDangNhapTask = new AsyncTask<String, Void, Integer>() {

			@Override
			protected Integer doInBackground(String... params) {
				int kq = 0;
				try {

					kq= new HeThongInvoike().register(FrmLogin.this);
							
					if(kq==0){
						kq = new HeThongInvoike().DangNhap(params[0], params[1], params[2]);						
					}
				} catch (Exception e) {
					kq = 2;
				}
				return kq;
			}

			@Override
			protected void onPostExecute(Integer result) {
				mProgressDialog.dismiss();
				if (result == 0) {
//					if (NetworkController._peer == null) {
						AccountDTO account = new AccountDTO();
						account.set_Username(CommonUtilities.nguoiDung.getTenDangNhap());
						account.setId(CommonUtilities.nguoiDung.getId());
						account.isThanhLapNhom = true;

						NetworkController.init("MES", 12322, account);
						ArrayList<Quyen> ruleList = ReadWriteFileController.readRule(getApplicationContext(),
								ReadWriteFileController.RULE_BASE_PATH);
						RoleDTO roleSangLapNhom = new RoleDTO("Người sáng lập nhóm", ruleList);
						NetworkController._peer.getAccount().addRole(roleSangLapNhom);
//					}
					NetworkController._statusLogin = Protocol.IS_ONLINE_OUTDOOR;
					Intent iMain = new Intent(getBaseContext(), od_MainActivity.class);
					startActivity(iMain);
				} else if (result == -1) {
					ShowLoginFail();
				} else if (result == 2) {
					ShowConnectFail();
				} else if(result==-2){
					MESApplication.showDialog(FrmLogin.this, "Error", "Kiểm tra lại máy chủ!");
				}else {
					ShowRegFail();
				}
			}

			@Override
			protected void onPreExecute() {
				mProgressDialog.show();
				NetworkController._statusLogin = Protocol.IS_ONLINE_OUTDOOR;
			}
		};
	}
	private void outDoorReset(){
		// out door
		CommonUtilities.contacts = null;
		CommonUtilities.subjects = null;
		CommonUtilities.idCayHienTai=-1;
		CommonUtilities.idNhomHienTai=-1;
		CommonUtilities.nguoiDung=null;
		CommonUtilities.soTinNhan=-1;
	}
}
